[% setvar title Exegesis 3: Operators %]
<div id="archive-notice">
    <h3>This file is part of the Perl 6 Archive</h3>
    <p>To see what is currently happening visit <a href="http://www.perl6.org/">http://www.perl6.org/</a></p>
</div>
<div class='pod'>
<pre>=encoding utf8</pre>
<a name='TITLE'></a><h1>TITLE</h1>
<p>Exegesis 3: Operators</p>
<a name='AUTHOR'></a><h1>AUTHOR</h1>
<p>Damian Conway &lt;<a href='mailto:damian@conway.org'>damian@conway.org</a>&gt;</p>
<a name='VERSION'></a><h1>VERSION</h1>
<pre>  Maintainer: Larry Wall &lt;<a href='mailto:larry@wall.org'>larry@wall.org</a>&gt;
  Date: 3 Oct 2001
  Last Modified: 29 May 2006
  Number: 3
  Version: 2</pre>
<p>[Update: Please note that this was written several years ago, and
a number of things have changed since then.  Rather than changing
the original document, we'll be inserting &quot;Update&quot; notes like this
one to tell you where the design has since evolved.  (For the better,
we hope).  In any event, for the latest Perl 6 design (or to figure out
any cryptic remarks below) you should read the Synopses, which are kept
very much more up-to-date than either the Apocalypses or Exegeses.]</p>
<ul>
<li><a name='Diamond lives (context-aware);'></a><i>Diamond lives (context-aware);</i></li>
<li><a name='Underscore space means concatenate; fat comma means pair;'></a><i>Underscore space means concatenate; fat comma means pair;</i></li>
<li><a name='A pre-star will flatten; colon-equals will bind;'></a><i>A pre-star will flatten; colon-equals will bind;</i></li>
<li><a name='And binary slash-slash yields left-most defined.'></a><i>And binary slash-slash yields left-most defined.</i></li>
<ul>
<li><a name='-- Sade, &quot;Smooth operator&quot; (Perl 6 remix)'></a>-- Sade, &quot;Smooth operator&quot; (Perl 6 remix)</li>
</ul>
</ul>
<p>[Update: For instance, despite the beautiful lyrics above, diamond
does not live, tilde is now the concatenate operator, and star
as a prefix operator has mutated into the <code>[,]</code> reduce operator.
(Though <code>*</code> in a signature still means &quot;slurpy&quot;.)]</p>
<p>In Apocalypse 3, Larry describes the changes that Perl 6 will make to
operators and their operations. As with all the Apocalypses, only the
new and different are presented -- just remember that the vast majority
of operator-related syntax and semantics will stay precisely as they
are in Perl 5.</p>
<a name='For example...'></a><h1>For example...</h1>
<p>To better understand those new and different aspects of Perl 6
operators, let's consider the following program. Suppose we wanted to
locate a particular data file in one or more directories, read the
first four lines of each such file, report and update their
information, and write them back to disk.</p>
<p>We could do that with this:</p>
<pre>    sub load_data ($filename ; $version, *@dirpath) {</pre>
<p>[Update: Optional args are now marked with a <code>?</code> suffix or a default
assignment.]</p>
<pre>        $version //= 1;
        @dirpath //= @last_dirpath // @std_dirpath // '.';
        @dirpath ^=~ s{([^/])$}{$1/};</pre>
<p>[Update: Hyper smartmatch is now <code>»~~«</code>.]</p>
<pre>        my %data;
        foreach my $prefix (@dirpath) {</pre>
<p>[Update: Now spelled:</p>
<pre>    for @dirpath -&gt; $prefix {</pre>
<p>]</p>
<pre>            my $filepath = $prefix _ $filename;</pre>
<p>[Update: Concatenation is now <code>~</code>.]</p>
<pre>            if (-w -r -e $filepath  and  100 &lt; -s $filepath &lt;= 1e6) {
                my $fh = open $filepath : mode=&gt;'rw' 
                    or die &quot;Something screwy with $filepath: $!&quot;;
                my ($name, $vers, $status, $costs) = &lt;$fh&gt;;</pre>
<p>[Update: iterating a filehandle is now <code>@$fh</code> or <code>=$fh</code>.]</p>
<pre>                next if $vers &lt; $version;
                $costs = [split /\s+/, $costs];
                %data{$filepath}{qw(fh name vers stat costs)} =
                                ($fh, $name, $vers, $status, $costs);</pre>
<p>[Update: <code>qw()</code> would now be a function call.  In general you'd use <code>&lt;...&gt;</code> instead.]</p>
<pre>            }
        }
        return %data;
    }
    my @StartOfFile is const = (0,0);</pre>
<p>[Update: Now you'd say</p>
<pre>    constant @StartOfFile = (0,0);</pre>
<p>or</p>
<pre>    my @StartOfFile is readonly = (0,0);</pre>
<p>]</p>
<pre>    sub save_data ( %data) {
        foreach my $data (values %data) {
            my $rest = &lt;$data.{fh}.irs(undef)&gt;</pre>
<p>[Update a constant hash subscript would now be <code>.&lt;fh&gt;</code> instead.
The <code>irs</code> property is now <code>newline</code>.]</p>
<pre>            seek $data.{fh}: *@StartOfFile;
            truncate $data.{fh}: 0;
            $data.{fh}.ofs(&quot;\n&quot;);
            print $data.{fh}: $data.{qw(name vers stat)}, _@{$data.{costs}}, $rest;</pre>
<p>[Update: instead of underline, <code>prefix:&lt;~&gt;</code> is now the string
context operator.]</p>
<pre>         }
    }
    my %data = load_data(filename=&gt;'weblog', version=&gt;1);
    my $is_active_bit is const = 0x0080;
    foreach my $file (keys %data) {
        print &quot;$file contains data on %data{$file}{name}\n&quot;;
        %data{$file}{stat} = %data{$file}{stat} ~ $is_active_bit;</pre>
<p>[Update: Since <code>~</code> is concatenation, numeric XOR is now <code>+^</code> instead.]</p>
<pre>        my @costs := @%data{$file}{costs};
        my $inflation;
        print &quot;Inflation rate: &quot; and $inflation = +&lt;&gt;
            until $inflation != NaN;
        @costs = map  { $_.value }
                 sort { $a.key &lt;=&gt; $b.key }
                 map  { amortize($_) =&gt; $_ }
                        @costs ^* $inflation;</pre>
<p>[Update: These closure arguments now require a comma after them.
(And a single-arg sort routine will do the Schwartzian Transform for
you automatically, but you can still do it this way.)]</p>
<pre>        my sub operator:&amp;sum; is prec(\&amp;operator:+($)) (*@list : $filter //= undef) {</pre>
<p>[Update: Syntax for declaring such an operator would now be:</p>
<pre>    my sub prefix:&lt;&amp;sum;&gt; is equiv(&amp;prefix:&lt;+&gt;) (*@list, +$filter) {</pre>
<p>However, there's a built-in <code>[+]</code> reduce operator that already does sums.]</p>
<pre>               reduce {$^a+$^b}  ($filter ?? grep &amp;$filter, @list :: @list);</pre>
<p>[Update: <code>??::</code> is now <code>??!!</code>.  But the syntax is illegal--you can't have
a lower-precedence comma inside a tighter-precedence <code>??!!</code>.]</p>
<pre>        }
        print &quot;Total expenditure: $( &amp;sum; @costs )\n&quot;;</pre>
<p>[Update: General interpolation is now just a closure, and print with a newline
is usually done with <code>say</code>, so you'd just write it:</p>
<pre>        say &quot;Total expenditure: { [+] @costs }&quot;;</pre>
<p>or just:</p>
<pre>        say &quot;Total expenditure: &quot;, [+] @costs;</pre>
<p>]</p>
<pre>        print &quot;Major expenditure: $( &amp;sum; @costs : {$^_ &gt;= 1000} )\n&quot;;</pre>
<p>[Update: An adverbial block may not have spaces between the colon and the
block.  Also, <code>$^_</code> is really just <code>$_</code>.]</p>
<pre>        print &quot;Minor expenditure: $( &amp;sum; @costs : {$^_ &lt; 1000} )\n&quot;;
        print &quot;Odd expenditures: @costs[1..Inf:2]\n&quot;; </pre>
<p>[Update: Now written <code>1..Inf:by(2)</code> or <code>1..*:by(2)</code>.]</p>
<pre>    }
    save_data(%data, log =&gt; {name=&gt;'metalog', vers=&gt;1, costs=&gt;[], stat=&gt;0});</pre>
<a name='I was bound under a flattening star'></a><h1>I was bound under a flattening star</h1>
<p>The first subroutine takes a filename and (optionally) a version number
and a list of directories to search:</p>
<pre>    sub load_data ($filename ; $version, *@dirpath) {</pre>
<p>Note that the directory path parameter is declared as <code>*@dirpath</code>, not
<code>@dirpath</code>. In Perl 6, declaring a parameter as an array (i.e
<code>@dirpath</code>) causes Perl to expect the corresponding argument will be
an actual array (or an array reference), not just any old list of
values. In other words, a <code>@</code> parameter in Perl 6 is like a <code>\@</code>
context specifier in Perl 5.</p>
<p>To allow <code>@dirpath</code> to accept a list of arguments, we have to use the
<i>list context specifier</i> -- unary <code>*</code> -- to tell Perl to &quot;slurp up&quot;
any remaining arguments into the <code>@dirpath</code> parameter.</p>
<p>This slurping-up process consists of flattening any arguments that are
arrays or hashes, and then assigning the resulting list of values,
together with any other scalar arguments, to the array (i.e. to
<code>@dirpath</code> in this example). In other words, a <code>*@</code> parameter in Perl
6 is like a <code>@</code> context specifier in Perl 5.</p>
<p>[Update: This flattening now happens lazily.]</p>
<a name='It's a setup'></a><h1>It's a setup</h1>
<p>In Perl 5, it's not uncommon to see people using the <code>||=</code> operator to
set up default values for subroutine parameters or input data:</p>
<pre>    $offset ||= 1;
    $suffix ||= $last_suffix || $default_suffix || '.txt';
    # etc.</pre>
<p>Of course, unless you're sure of your range of values, this can go
horribly wrong -- specifically, if the variable being initialized
already has a valid value that Perl happens to consider false (i.e if
<code>$suffix</code> or <code>$last_suffix</code> or <code>$default_suffix</code> contained an empty
string, or the offset really <i>was</i> meant to be zero).</p>
<p>So people have been forced to write default initializers like this:</p>
<pre>    $offset = 1 unless defined $offset;</pre>
<p>which is OK for a single alternative, but quickly becomes unwieldy when
there are several alternatives:</p>
<pre>    $suffix = $last_suffix    unless defined $suffix;
    $suffix = $default_suffix unless defined $suffix;
    $suffix = '.txt'          unless defined $suffix;</pre>
<p>Perl 6 introduces a binary 'default' operator -- <code>//</code> -- that solves
this problem. The default operator evaluates to its left operand if
that operand is defined, otherwise it evaluates to its right operand.
When chained together, a sequence of <code>//</code> operators evaluates to the
first operand in the sequence that is defined. And, of course, the
assignment variant -- <code>//=</code> -- only assigns to its lvalue if that
lvalue is currently undefined.</p>
<p>The symbol for the operator was chosen to be reminiscent of a <code>||</code>,
but one that's taking a slightly different angle on things.</p>
<p>So <code>&amp;load_data</code> ensures that its parameters have sensible defaults
like this:</p>
<pre>    $version //= 1;
    @dirpath //= @last_dirpath // @std_dirpath // '.';</pre>
<p>Note that it will also be possible to provide default values directly
in the specification of optional parameters, probably like this:</p>
<pre>    sub load_data ($filename ; $version //= 1, *@dirpath //= @std_dirpath) {...}</pre>
<a name='...and context for all'></a><h1>...and context for all</h1>
<p>As if it weren't broken enough already, there's another nasty problem
with using <code>||</code> to build default initializers in Perl 5. Namely, that
it doesn't work quite as one might expect for arrays or hashes either.</p>
<p>If you write:</p>
<pre>    @last_mailing_list = ('me', '<a href='mailto:my@shadow'>my@shadow</a>');
    # and later...
    @mailing_list = @last_mailing_list || @std_mailing_list;</pre>
<p>then you get a nasty surprise: In Perl 5, <code>||</code> (and <code>&amp;&amp;</code>, for that
matter) always evaluates its left argument in <i>scalar</i> context. And in
a scalar context an array evaluates to the number of elements it
contains, so <code>@last_mailing_list</code> evaluates to <code>2</code>. And that's what's
assigned to <code>@mailing_list</code> instead of the actual two elements.</p>
<p>Perl 6 fixes that problem, too. In Perl 6, both sides of an <code>||</code> (or a
<code>&amp;&amp;</code> or a <code>//</code>) are evaluated in the same context as the complete
expression. That means, in the example above, <code>@last_mailing_list</code> is
evaluated in list context, so its two elements are assigned to
<code>@mailing_list</code>, as expected.</p>
<a name='Substitute our vector, Victor!'></a><h1>Substitute our vector, Victor!</h1>
<p>The next step in <code>&amp;load_data</code> is to ensure that each path in
<code>@dirpath</code> ends in a directory separator. In Perl 5, we might do that
with:</p>
<pre>    s{([^/])$}{$1/} foreach @dirpath;</pre>
<p>but Perl 6 gives us another alternative: hyper-operators.</p>
<p>Normally, when an array is an operand of a unary or binary operator, it
is evaluated in the scalar context imposed by the operator and yields a
single result. For example, if we execute:</p>
<pre>    $account_balance   = @credits + @debits;
    $biblical_metaphor = @sheep - @goats;</pre>
<p>then <code>$account_balance</code> gets the total number of credits plus the
number of debits, and <code>$biblical_metaphor</code> gets the numerical
difference between the number of <code>@sheep</code> and <code>@goats</code>.</p>
<p>That's fine, but this scalar coercion also happens when the operation
is in a list context:</p>
<pre>    @account_balances   = @credits + @debits;
    @biblical_metaphors = @sheep - @goats;</pre>
<p>Many people find it counter-intuitive that these statements each
produce the same scalar result as before and then assign it as the
single element of the respective lvalue arrays.</p>
<p>It would be more reasonable to expect these to act like:</p>
<pre>    # Perl 5 code...
    @account_balances   =
            map { $credits[$_] + $debits[$_] } 0..max($#credits,$#debits);
    @biblical_metaphors = 
            map { $sheep[$_] - $goats[$_] } 0..max($#sheep,$#goats);</pre>
<p>That is, to apply the operation element-by-element, pairwise along the
two arrays.</p>
<p>Perl 6 makes that possible, though <i>not</i> by changing the list context
behavior of the existing operators. Instead, Perl 6 provides a &quot;vector&quot;
version of each binary operator. Each uses the same symbol as the
corresponding scalar operator, but with a caret (<code>^</code>) dangled in front
of it. Hence to get the one-to-one addition of corresponding credits
and debits, and the list of differences between pairs of sheep and
goats, we can write:</p>
<pre>    @account_balances   = @credits ^+ @debits;
    @biblical_metaphors = @sheep ^- @goats;</pre>
<p>[Update: Hyper operators are now written with <code>»...«</code> quotes.]</p>
<p>This works for <i>all</i> unary and binary operators, including those that
are user-defined. If the two arguments are of different lengths, the
operator Does What You Mean (which, depending on the operator, might
involve padding with ones, zeroes or <code>undef</code>'s, or throwing an
exception).</p>
<p>If one of the arguments is a scalar, that operand is replicated as many
times as is necessary. For example:</p>
<pre>    @interest = @account_balances ^* $interest_rate;</pre>
<p>Which brings us back to the problem of appending those directory
separators. The &quot;pattern association&quot; operator (<code>=~</code>) can also be
vectorized by prepending a caret, so we can apply the necessary
substitution to each element in the <code>@dirpath</code> array like this:</p>
<pre>    @dirpath ^=~ s{([^/])$}{$1/};</pre>
<a name='(Pre)fixing those filenames'></a><h1>(Pre)fixing those filenames</h1>
<p>Having ensured everything is set up correctly, <code>&amp;load_data</code> then
processes each candidate file in turn, accumulating data as it goes:</p>
<pre>    my %data;
    foreach my $prefix (@dirpath) {</pre>
<p>The first step is to create the full file path, by prefixing the
current directory path to the basic filename:</p>
<pre>        my $filepath = $prefix _ $filename;</pre>
<p>And here we see the new Perl 6 string concatenation operator:
underscore. And yes, we realize it's going to take time to get used to.
It may help to think of it as the old dot operator under extreme
acceleration.</p>
<p>Underscore is still a valid identifier character, so you need to be
careful about spacing it from a preceding or following identifier (just
as you've always have with the <code>x</code> or <code>eq</code> operators):</p>
<pre>    # Perl 6 code                   # Meaning
    $name = getTitle _ getName;     # getTitle() . getName()
    $name = getTitle_ getName;      # getTitle_(getName())
    $name = getTitle _getName;      # getTitle(_getName())
    $name = getTitle_getName;       # getTitle_getName()</pre>
<p>In Perl 6, there's also a unary form of <code>_</code>. We'll get to that
<i><a href='#String 'em up together'>a little later</a></i>.</p>
<p>[Update: Changing to <code>~</code> for these solved the identifier problem.]</p>
<a name='Don't break the chain'></a><h1>Don't break the chain</h1>
<p>Of course, we only want to load the file's data if the file exists, is
readable and writable, and isn't too big or too small (say, no less
than 100 bytes and no more than a million). In Perl 5 that would be:</p>
<pre>    if (-e $filepath  &amp;&amp;  -r $filepath  &amp;&amp;  -w $filepath  and
        100 &lt; -s $filepath  &amp;&amp;  -s $filepath &lt;= 1e6) {...</pre>
<p>which has far too many <code>&amp;&amp;</code>'s and <code>$filepath</code>'s for its own good.</p>
<p>In Perl 6, the same set of tests can be considerably abbreviated by
taking advantage of two new types of operator chaining:</p>
<pre>    if (-w -r -e $filepath  and  100 &lt; -s $filepath &lt;= 1e6) {...</pre>
<p>First, the <code>-X</code> file test operators now all return a special object
that evaluates true or false in a boolean context but is really an
encapsulated <code>stat</code> buffer, to which subsequent file tests can be
applied. So now you can put as many file tests as you like in front of
a single filename or filehandle and they must all be true for the whole
expression to be true. Note that because these are really nested calls
to the various file tests (i.e. <code>-w(-r(-e($filepath)))</code>), the series
of tests are effectively evaluated in right-to-left order.</p>
<p>The test of the file size uses another new form of chaining that Perl 6
supports: multiway comparisons. An expression like
<code>100 &lt; -s $filepath &lt;= 1e6</code> isn't even legal Perl 5, but it
Does The Right Thing in Perl 6. More importantly, it short-circuits if
the first comparison fails and will evaluate each operand only once.</p>
<a name='Open for business'></a><h1>Open for business</h1>
<p>Having verified the file's suitability, we open it for reading and
writing:</p>
<pre>    my $fh = open $filepath : mode=&gt;'rw' 
        or die &quot;Something screwy with $filepath: $!&quot;;</pre>
<p>The <code>: mode=&gt;'rw'</code> is an <i>adverbial modifier</i> on the <code>open</code>.
We'll see more adverbs shortly.</p>
<p>The <code>$!</code> variable is exactly what you think it is: a container for the
last system error message. It's also considerably <i>more</i> than you
think it is, since it's also taken over the roles of <code>$?</code> and <code>$@</code>,
to become the One True Error Variable.</p>
<a name='Applied laziness 101'></a><h1>Applied laziness 101</h1>
<p>Contrary to earlier rumors, the &quot;diamond&quot; input operator is alive and
well and living in Perl 6 (yes, the Perl Ministry of Truth is even now
rewriting Apocalypse 2 to correct the ... err ... &quot;printing error&quot; ...
that announced <code>&lt;&gt;</code> would be purged from the language).</p>
<p>[Update: The Ministry of Truth was caught in its Big Lie, and <code>&lt;&gt;</code>
is now a <code>qw//</code>.]</p>
<p>So we can happily proceed to read in four lines of data:</p>
<pre>    my ($name, $vers, $status, $costs) = &lt;$fh&gt;;</pre>
<p>Now, writing something like this is a common Perl 5 mistake -- the list
context imposed by the list of lvalues induces <code>&lt;$fhE&gt;</code> to read
the entire file, create a list of (possibly hundreds of thousands of)
lines, assign the first four to the specified variables, and throw the
rest away. That's rarely the desired effect.</p>
<p>In Perl 6, this statement works as it should. That is, it works out how
many values the lvalue list is actually expecting and then reads only
that many lines from the file.</p>
<p>Of course, if we'd written:</p>
<pre>    my ($name, $vers, $status, $costs, @and_the_rest) = &lt;$fh&gt;;</pre>
<p>then the entire file <i>would</i> have been read.</p>
<p>[Update: It works a bit differently from that now, but has the same
effect.  Lists are evaluated lazily by default, so the assignment only
ever ends up demanding however many lines it needs from the iterator.
But it's misleading to say that &quot;It works out how many values the
lvalue list is expecting&quot; as if that were a separate step in advance.</p>
<a name='And now for something completely the same (well, almost)'></a><h1>And now for something completely the same (well, almost)</h1>
<p>Apart from the new sigil syntax (i.e. hashes now keep their <code>%</code> signs
no matter what they're doing), the remainder of <code>&amp;load_data</code> is
exactly as it would have been if we'd written it in Perl 5.</p>
<p>We skip to the next file if the current file's version is wrong.
Otherwise, we split the costs line into an array of
whitespace-delimited values, and then save everything (including the
still-open filehandle) in a nested hash within <code>%data</code>:</p>
<pre>            next if $vers &lt; $version;
            $costs = [split /\s+/, $costs];
            %data{$filepath}{qw(fh name vers stat costs)} =
                          ($fh, $name, $vers, $status, $costs);
            }
        }</pre>
<p>Then, once we've iterated over all the directories in <code>@dirpath</code>, we
return the accumulated data:</p>
<pre>        return %data;
    }</pre>
<a name='The virtue of constancy'></a><h1>The virtue of constancy</h1>
<p>Perl 6 variables can be used as constants:</p>
<pre>    my @StartOfFile is const = (0,0);</pre>
<p>which is a great way to give logical names to literal values, but
ensure that those named values aren't accidentally changed in some
other part of the code.</p>
<a name='Writing it back'></a><h1>Writing it back</h1>
<p>When the data is eventually saved, we'll be passing it to the
<code>&amp;save_data</code> subroutine in a hash. If we expected the hash to be a
real hash variable (or a reference to one), we'd write:</p>
<pre>    sub save_data (%data) {...</pre>
<p>But since we want to allow for the possibility that the hash is created
on the fly (e.g. from a hash-like list of values), we need to use the
slurp-it-all-up list context asterisk again:</p>
<pre>    sub save_data (*%data) {...</pre>
<a name='From each according to its ability ...'></a><h1>From each according to its ability ...</h1>
<p>We then grab each datum for each file with the usual
<code>foreach ...  values ... </code> construct:</p>
<pre>        foreach my $data (values %data) {</pre>
<p>and go about saving the data to file.</p>
<p>[Update: Now &quot;<code>for %data.values -&gt; $data {...}</code>&quot;.]</p>
<a name='Your all-in-one input supplier'></a><h1>Your all-in-one input supplier</h1>
<p>Because the Perl 6 &quot;diamond&quot; operator can take an arbitrary expression
as its argument, it's possible to set a filehandle to read an entire
file <i>and</i> do the actual reading, all in a single statement:</p>
<pre>    my $rest = &lt;$data.{fh}.irs(undef)&gt;</pre>
<p>The variable <code>$data</code> stores a reference to a hash, so to dereference
it and access the <code>'fh'</code> entry, we use the Perl 6 dereferencing
operator (dot) and write: <code>$data.{fh}</code>. In practice, we could leave
out the operator and just write <code>$data{fh}</code>, since Perl can infer from
the <code>$</code> sigil that we're accessing the hash through a reference held
in a scalar. In fact, in Perl 6 the only place you <i>must</i> use an
explicit <code>.</code> dereferencer is in a method call. But it never hurts to
say exactly what you mean, and there's certainly no difference in
performance if you do choose to use the dot.</p>
<p>The <code>.irs(undef)</code> method call then sets the input record separator of
the filehandle (i.e. the Perl 6 equivalent of <code>$/</code>) to <code>undef</code>,
causing the next read operation to return the remaining contents of the
file. And because the filehandle's <code>irs</code> method returns its own
invocant -- i.e. the filehandle reference -- the entire expression can
be used within the angle brackets of the read.</p>
<p>[Update: The use of parameterized methods for object modifiers is
deprecated in favor of the <code>but</code> operator.  However, this sort of
thing should be set on the filehandle object outside the loop in
any event.]</p>
<p>A variation on this technique allows a Perl program to do a shell-like
read-from-filename just as easily:</p>
<pre>    my $next_line = &lt;open $filename or die&gt;;</pre>
<p>or, indeed, to read the whole file:</p>
<pre>    my $all_lines = &lt; open $filename : irs=&gt;undef &gt;;</pre>
<p>[Update: Make it:</p>
<pre>    my $all_lines = slurp $filename;</pre>
<p>]</p>
<a name='Seek and ye shall flatten'></a><h1>Seek and ye shall flatten</h1>
<p>Having grabbed the entire file, we now rewind and truncate it, in
preparation for writing it back:</p>
<pre>    seek $data.{fh}: *@StartOfFile;
    truncate $data.{fh}: 0;</pre>
<p>You're probably wondering what's with the asterisk ... unless you've
ever tried to write:</p>
<pre>    seek $filehandle, @where_and_whence;</pre>
<p>in Perl 5 and gotten back the annoying <code>&quot;Not enough arguments for
seek&quot;</code> exception. The problem is that <code>seek</code> expects three distinct
scalars as arguments (as if it had a Perl 5 prototype of <code>seek($$$)</code>),
and it's too fastidious to flatten the proffered array in order to get
them.</p>
<p>It's handy to wrap the magical <code>0,0</code> arguments of the <code>seek</code> in a
single array (so we no longer have to remember this particular
incantation), but to use such an array in Perl 5 we would then have to
write:</p>
<pre>    seek $data-&gt;{fh}, $StartOfFile[0], $StartOfFile[1];    # Perl 5</pre>
<p>In Perl 6 that's not a problem, because we have <code>*</code> -- the list
context specifier. When used in an argument list, it takes whatever you
give it (typically an array or hash) and flattens it. So:</p>
<pre>    seek $data.{fh}: *@StartOfFile;                        # Perl 6</pre>
<p>massages the single array into a list of two scalars, as <code>seek</code>
requires.</p>
<p>[Update: Now use <code>[,]</code> to &quot;reduce with comma&quot;.]</p>
<p>Oh, and yes, that <i>is</i> the adverbial colon again. In Perl 6, <code>seek</code>
and <code>truncate</code> are both methods of filehandle objects. So we can
either call them as:</p>
<pre>    $data.{fh}.seek(*@StartOfFile);
    $data.{fh}.truncate(0);</pre>
<p>Or use the &quot;indirect object&quot; syntax:</p>
<pre>    seek $data.{fh}: *@StartOfFile;
    truncate $data.{fh}: 0;</pre>
<p>And that's where the colon comes in. Another of its many uses in Perl 6
is to separate &quot;indirect object&quot; arguments (e.g. filehandles) from the
rest of the argument list. The main place you'll see colons guarding
indirect objects is in <code>print</code> statements (as described in the next
section).</p>
<p>[Update: We still use an indirect object colon, but it is no longer construed
as an adverbial colon.  Also, the examples above would require parens around
the indirect object.]</p>
<a name='It is written...'></a><h1>It is written...</h1>
<p>Finally, <code>&amp;save_data</code> has everything ready and can write the four
fields and the rest of the file back to disk. First, it sets the output
field separator for the filehandle (i.e. the equivalent of Perl 5's
<code>$,</code> variable) to inject newlines between elements:</p>
<pre>    $data.{fh}.ofs(&quot;\n&quot;);</pre>
<p>Then it prints the fields to the filehandle:</p>
<pre>    print $data.{fh}: $data.{qw(name vers stat)}, _@{$data.{costs}}, $rest;</pre>
<p>Note the use of the adverbial colon after <code>$data.{fh}</code> to separate the
filehandle argument from the items to be printed. The colon is required
because it's how Perl 6 eliminates the nasty ambiguity inherent in the
&quot;indirect object&quot; syntax. In Perl 5, something like:</p>
<pre>    print foo bar;</pre>
<p>could conceivably mean:</p>
<pre>    print {foo} (bar);    # Perl 5: print result of bar() to filehandle foo</pre>
<p>or</p>
<pre>    print ( foo(bar) );   # Perl 5: print foo() of bar() to default filehandle</pre>
<p>or even:</p>
<pre>    print ( bar-&gt;foo );   # Perl 5: call method foo() on object returned by
                          #         bar() and print result to default filehandle</pre>
<p>In Perl 6, there is no confusion, because each indirect object must
followed by a colon. So in Perl 6:</p>
<pre>    print foo bar;</pre>
<p>can only mean:</p>
<pre>    print ( foo(bar) );   # Perl 6: print foo() of bar() to default filehandle</pre>
<p>and to get the other two meanings we'd have to write:</p>
<pre>    print foo: bar;       # Perl 6: print result of bar() to filehandle foo()
                          #         (foo() not foo, since there are no
                          #          bareword filehandles in Perl 6)</pre>
<p>and:</p>
<pre>    print foo bar: ;      # Perl 6: call method foo() on object returned by
                          #         bar() and print result to default filehandle</pre>
<p>In fact, the colon has an even wider range of use, as a general-purpose
&quot;adverb marker&quot;; a notion we will explore more fully
<i><a href='#Would you like an adverb with that?'>below</a></i>.</p>
<a name='String 'em up together'></a><h1>String 'em up together</h1>
<p>The printed arguments are: a hash slice:</p>
<pre>    $data.{qw(name vers stat)},</pre>
<p>[Update: Now generally written: <code>$data&lt;name vers stat&gt;</code>.]</p>
<p>a stringified dereferenced nested array:</p>
<pre>     _@{$data.{costs}},</pre>
<p>[Update: Now written: <code>~@($data&lt;costs&gt;)</code>.]</p>
<p>and a scalar:</p>
<pre>    $rest;</pre>
<p>The new hash slice syntax was explained in the previous
Apocalypse/Exegesis, and the scalar is just a scalar, but what was the
middle thing again?</p>
<p>Well, <code>$data.{costs}</code> is just a regular Perl 6 access to the
<code>'costs'</code> entry of the hash referred to by <code>$data</code>. That entry
contains the array reference that was the result of splitting <code>$cost</code>
in <i><a href='#And now for something completely the same (well, almost)'>in <code>&amp;load_data</code></a></i>).</p>
<p>So to get the actual array itself, we can prefix the array reference
with a <code>@</code> sigil (though, technically, we don't <i>have</i> to: in Perl 6
arrays and array references are interchangeable in scalar context).</p>
<p>That gives us <code>@{$data.{costs}}</code>. The only remaining difficulty is
that when we print the list of items produced by <code>@{$data.{costs}}</code>,
they are subject to the output field separator. Which we just set to
newline.</p>
<p>But what we want is for them to appear on the <i>same</i> line, with a
space between each.</p>
<p>Well ... evaluating a list in a string context does precisely that, so
we could just write:</p>
<pre>    &quot;@{$data.{costs}}&quot;    # evaluate array in string context</pre>
<p>But Perl 6 has another alternative to offer us -- the unary underscore
operator. Binary underscore is string concatenation, so it shouldn't be
too surprising that unary underscore is the stringification operator
(think: concatenation with a null string). Prefixing any expression
with an underscore forces it to be evaluated in string context:</p>
<pre>    _@{$data{costs}}     # evaluate array in string context</pre>
<p>Which, in this case, conveniently inserts the required spaces between
the elements of the costs array.</p>
<a name='A parameter by any other name'></a><h1>A parameter by any other name</h1>
<p>Now that the I/O is organized, we can get down to the actual
processing. First, we load the data:</p>
<pre>    my %data = load_data(filename=&gt;'weblog', version=&gt;1);</pre>
<p>Note that we're using named arguments here. This attempt would blow up
badly in Perl 5, because we didn't set <code>&amp;load_data</code> up to expect a
hash-like list of arguments. But it works fine in Perl 6 for two
reasons:</p>
<ul>
<li><a name='1.'></a>1.</li>
<p>Because we <i>did</i> set up <code>&amp;load_data</code> with named parameters;</p>
<p>and</p>
<li><a name='2.'></a>2.</li>
<p>Because the <code>=&gt;</code> operator isn't in Kansas anymore.</p>
</ul>
<p>In Perl 5, <code>=&gt;</code> is just an up-market comma with a single minor
talent: It stringifies its left operand if that operand is a bareword.</p>
<p>In Perl 6, <code>=&gt;</code> is a fully-fledged anonymous object constructor --
like <code>[...]</code> and <code>{...}</code>. The objects it constructs are called
&quot;pairs&quot; and they consist of a key (the left operand of the <code>=&gt;</code>),
and a value (the right operand). The key is still stringified if it's a
valid identifier, but both the key and the value can be <i>any</i> kind of
Perl data structure. They are accessed via the pair object's <code>key</code> and
<code>value</code> methods:</p>
<pre>    my $pair_ref = [1..9] =&gt; &quot;digit&quot;;
    print $pair_ref.value;      # prints &quot;digit&quot;
    print $pair_ref.key.[3];    # prints 4</pre>
<p>So, rather than getting four arguments:</p>
<pre>    load_data('filename', 'weblog', 'version', 1);    # Perl 5 semantics</pre>
<p><code>&amp;load_data</code> gets just two arguments, each of which is a reference to
a pair:</p>
<pre>    load_data( $pair_ref1, $pair_ref2);               # Perl 6 semantics</pre>
<p>When the subroutine dispatch mechanism detects one or more pairs as
arguments to a subroutine with named parameters, it examines the keys
of the pairs and binds their values to the correspondingly named
parameters -- no matter what order the paired arguments originally
appeared in. Any remaining non-pair arguments are then bound to the
remaining parameters in left-to-right order.</p>
<p>So we could call <code>&amp;load_data</code> in any of the following ways:</p>
<pre>    load_data(filename=&gt;'weblog', version=&gt;1);  # named
    load_data(version=&gt;1, filename=&gt;'weblog');  # named (order doesn't matter)
    load_data('weblog', 1);                     # positional (order matters)</pre>
<p>There are numerous other uses for pairs, one of which we'll see
<i><a href='#Schwartzian pairs'>shortly</a></i>.</p>
<a name='Please queue for processing'></a><h1>Please queue for processing</h1>
<p>Having loaded the data, we go into a loop and iterate over each file's
information. First, we announce the file and its internal name:</p>
<pre>    foreach my $file (keys %data) {
        print &quot;$file contains data on %data{$file}{name}\n&quot;;</pre>
<p>[Update:</p>
<pre>    for %data.kv -&gt; $file, $entry {
        say &quot;$file contains data on $entry&lt;name&gt;&quot;;</pre>
<p>]</p>
<a name='The Xor-twist'></a><h1>The Xor-twist</h1>
<p>Then we toggle the &quot;is active&quot; status bit (the eighth bit) for each
file. To flip that single bit without changing any of the other status
bits, we bitwise-xor the status bitset against the bitstring
<code>0000000010000000</code>. Each bit xor'd against a zero stays as it is
(0 xor 0 --&gt; 0; 1 xor 0 --&gt; 1), while xor'ing the eighth bit
against 1 complements it (0 xor 1 --&gt; 1; 1 xor 1 --&gt; 0).</p>
<p>But because the caret has been appropriated as the Perl 6
<i><a href='#Substitute our vector, Victor!'>hyper-operator prefix</a></i>,
it will no longer be used as bitwise xor. Instead, binary
tilde will be used:</p>
<pre>    %data{$file}{stat} = %data{$file}{stat} ~ $is_active_bit;</pre>
<p>This is actually an improvement in syntactic consistency since bitwise
xor (now binary <code>~</code>) and bitwise complement (still unary <code>~</code>) are
mathematically related: <code>~x</code> is <code>(-1~x)</code>.</p>
<p>[Update: Symbolic XORs and NOTs now consistently use ^ rather than ~.]</p>
<p>Note that we <i>could</i> have used the assignment variant of binary <code>~</code>:</p>
<pre>    %data{$file}{stat} ~= $is_active_bit;     # flip only bit 8 of status bitset</pre>
<p>[Update: Is now <code>+^=</code> for the numeric XOR assignment operator.]</p>
<p>but that's probably best avoided due to its confusability with the much
commoner &quot;pattern association&quot; operator:</p>
<pre>    %data{$file}{stat} =~ $is_active_bit;     # match if status bitset is &quot;128&quot;</pre>
<p>By the way, there is also a high precedence logical xor operator in
Perl 6. You guessed it: <code>~~</code>.</p>
<p>[Update: No, that's now the smart-match operator, just to avoid the =~
confusion.  High precedence XOR is <code>^^</code> instead.]</p>
<p>This finally fills the strange gap in
Perl's logical operator set:</p>
<pre>        Binary (low) | Binary (high) |    Bitwise
       ______________|_______________|_____________
                     |               |
            or       |      ||       |      |
                     |               |
            and      |      &amp;&amp;       |      &amp;
                     |               |
            xor      |      ~~       |      ~
                     |               |</pre>
<p>And it will also help to reduce programmer stress by allowing us to
write:</p>
<pre>    $make = $money ~~ $fast;</pre>
<p>instead of (the clearly over-excited):</p>
<pre>    $make = !$money != !$fast;</pre>
<a name='Bound for glory'></a><h1>Bound for glory</h1>
<p>In both Perl 5 and 6, it's possible to create an <i>alias</i> for a
variable. For example, the subroutine:</p>
<pre>    sub increment { $_[0]++ }           # Perl 5
    sub increment { @_[0]++ }           # Perl 6</pre>
<p>works because the elements of <code>@_</code> become aliases for whatever
variable is passed as their corresponding argument. Similarly, one can
use a <code>for</code> to implement a Pascal-ish <code>with</code>:</p>
<pre>    for my $age ( $person[$n]{data}{personal}{time_dependent}{age} ) {
        if    ($age &lt; 12) { print &quot;Child&quot; }
        elsif ($age &lt; 18) { print &quot;Adolescent&quot; }
        elsif ($age &lt; 25) { print &quot;Junior citizen&quot; }
        elsif ($age &lt; 65) { print &quot;Citizen&quot; }
        else              { print &quot;Senior citizen&quot; }
    }</pre>
<p>Perl 6 provides a more direct mechanism for aliasing one variable to
another in this way: the <code>:=</code> (or &quot;binding&quot;) operator. For example, we
could rewrite the previous example like so in Perl 6:</p>
<pre>    my $age := $person[$n]{data}{personal}{time_dependent}{age};</pre>
<p>[Update: Make that:</p>
<pre>    my $age := $person[$n]&lt;data&gt;&lt;personal&gt;&lt;time_dependent&gt;&lt;age&gt;;</pre>
<p>]</p>
<pre>    if    ($age &lt; 12) { print &quot;Child&quot; }
    elsif ($age &lt; 18) { print &quot;Adolescent&quot; }
    elsif ($age &lt; 25) { print &quot;Junior citizen&quot; }
    elsif ($age &lt; 65) { print &quot;Citizen&quot; }
    else              { print &quot;Senior citizen&quot; }</pre>
<p>Bound aliases are particularly useful for temporarily giving a
conveniently short identifier to a variable with a long or complex
name. Scalars, arrays, hashes and even subroutines may all be given
less sequipedalian names in this way:</p>
<pre>        my   @list := @They::never::would::be::missed::No_never_would_be_missed;
        our  %plan := %{$planning.[$planner].{planned}.[$planet]};
        temp &amp;rule := &amp;FulfilMyGrandMegalomanicalDestinyBwahHaHaHaaaa;</pre>
<p>In our example program, we use aliasing to avoid having to write
<code>@%data{$file}{costs}</code> everywhere:</p>
<pre>    my @costs := @%data{$file}{costs};</pre>
<p>An important feature of the binding operator is that the lvalue (or
lvalues) on the left side form a context specification for the rvalue
(or rvalues) on the right side. It's as if the lvalues were the
parameters of an invisible subroutine, and the rvalues were the
corresponding arguments being passed to it. So, for example, we could
also have written:</p>
<pre>    my @costs := %data{$file}{costs};</pre>
<p>(i.e. without the <code>@</code> dereferencer) because the lvalue <i>expects</i> an
array as the corresponding rvalue, so Perl 6 automatically dereferences
the array reference in <code>%data{$file}{costs}</code> to provide that.</p>
<p>More interestingly, if we have both lvalue and rvalue lists, then each
of the rvalues is evaluated in the context specified by its
corresponding lvalue. For example:</p>
<pre>    (@x, @y) := (@a, @b);</pre>
<p>aliases <code>@x</code> to <code>@a</code>, and <code>@y</code> to <code>@b</code>, because <code>@</code>'s on the left
act like <code>@</code> parameters, which require -- and bind to -- an
unflattened array as their corresponding argument. Likewise:</p>
<pre>    ($x, %y, @z) := (1, {b=&gt;2}, %c{list});</pre>
<p>binds <code>$x</code> to the value <code>1</code> (i.e. <code>$x</code> becomes a constant), <code>%y</code> to
the anonymous hash constructed by <code>{b=&gt;2}</code>, and <code>@z</code> to the array
referred to by <code>%c{list}</code>. In other words, it's the same set of
bindings we'd see if we wrote:</p>
<pre>    sub foo($x, %y, @z) {...}
    foo(1, {b=&gt;2}, %c{list});</pre>
<p>except that the <code>:=</code> binding takes effect in the current scope.</p>
<p>And because <code>:=</code> works that way, we can also use the flattening
operator (unary <code>*</code>) on either side of such bindings. For example:</p>
<pre>    (@x, *@y) := (@a, $b, @c, %d);</pre>
<p>aliases <code>@x</code> to <code>@a</code>, and causes <code>@y</code> to bind to the remainder of
the lvalues -- by flattening out <code>$b</code>, <code>@c</code>, and <code>%d</code> into a list
and then slurping up all their components together.</p>
<p>Note that <code>@y</code> is still an <i>alias</i> for those various slurped
components. So <code>@y[0]</code> is an alias for <code>$b</code>, <code>@y[<a href='mailto:1..@c.length'>1..@c.length</a>]</code> are
aliases for the elements of <code>@c</code>, and the remaining elements of <code>@y</code>
are aliases for the interlaced keys and values of <code>%d</code>.</p>
<p>When the star is on the other side of the binding, as in:</p>
<pre>    ($x, $y) := (*@a);</pre>
<p>[Update: Now <code>[,]@a</code> instead.]</p>
<p>then <code>@a</code> is flattened before it is bound, so <code>$x</code> becomes an alias
for <code>@a[0]</code> and <code>$y</code> becomes an alias for <code>@a[1]</code>.</p>
<p>The binding operator will have many uses in Perl 6 (most of which we
probably haven't even thought of yet), but one of the commonest will
almost certainly be as an easy way to swap two arrays efficiently:</p>
<pre>    (@x, @y) := (@y, @x);</pre>
<p>Yet another way to think about the binding operator is to consider it
as a sanitized version of those dreaded Perl 5 typeglob assignments.
That is:</p>
<pre>    $age := $person[$n]{data}{personal}{time_dependent}{age};</pre>
<p>is the same as Perl 5's:</p>
<pre>    *age = \$person-&gt;[$n]{data}{personal}{time_dependent}{age};</pre>
<p>except that it also works if <code>$age</code> is declared as a lexical.</p>
<p>Oh, and binding is much safer than typeglobbing was, because it
explicitly requires that
<code>$person[$n]{data}{personal}{time_dependent}{age}</code> evaluate to a
scalar, whereas the Perl 5 typeglob version would happily (and
silently!) replace <code>@age</code>, <code>%age</code>, or even <code>&amp;age</code> if the rvalue
happened to produce a reference to an array, hash, or subroutine
instead of a scalar.</p>
<a name='Better living through sigils'></a><h1>Better living through sigils</h1>
<p>We should also note that the binding of the <code>@costs</code> array:</p>
<pre>    my @costs := @%data{$file}{costs};</pre>
<p>shows yet another case where Perl 6's sigil semantics are much
DWIM-mier than those of Perl 5.</p>
<p>In Perl 5 we would probably have written that as:</p>
<pre>        local *costs = \ @$data{$file}{costs};</pre>
<p>and then spent some considerable time puzzling out why it wasn't
working, before realising that we'd actually meant:</p>
<pre>        local *costs = \ @{$data{$file}{costs}};</pre>
<p>instead.</p>
<p>That's because, in Perl 5, the precedence of a hash key is relatively
low, so:</p>
<pre>    @$data{$file}{costs}    # means: @{$data}{$file}{costs}
                            # i.e. (invalid attempt to) access the 'costs'
                            # key of a one-element slice of the hash
                            # referred to by $data
                            # problem is: slices don't have hash keys</pre>
<p>whereas:</p>
<pre>    @{$data{$file}{costs}}  # means: @{ $data{$file}{costs} }
                            # i.e. dereference of array referred to by
                            # $data{$file}{costs}</pre>
<p>The problem simply doesn't arise in Perl 6, where the two would be
written quite distinctly, as:</p>
<pre>    %data{@($file)}{costs}  # means: (%data{@($file)}).{costs}
                            # (still an error in Perl 6)</pre>
<p>and:</p>
<pre>    @%data{$file}{costs}    # means: @{ %data{$file}{costs} }
                            # i.e. dereference of array referred to by
                            # %data{$file}{costs}</pre>
<p>respectively.</p>
<p>[Update: You now have to write <code>@(%...)</code> instead.  <code>@%</code> would be
construed as an illegal sigil.  You can also write it using a <code>.@</code> postfix.]</p>
<a name='That's not a number...now that's a number!'></a><h1>That's not a number...now <i>that's</i> a number!</h1>
<p>One of the perennial problems with Perl 5 is how to read in a number.
Or rather, how to read in a string...and then be sure that it contains
a valid number. Currently, most people read in the string and then
either just assume it's a number (optimism) or use the regexes found in
perlfaq4 or Regexp::Common to make sure (cynicism).</p>
<p>Perl 6 offers a simpler, built-in mechanism.</p>
<p>Just as the unary version of binary underscore (<code>_</code>) is Perl 6's
explicit stringification specifier, so to the unary version of binary
plus is Perl 6's explicit numerifier. That is, prefixing an expression
with unary <code>+</code> evaluates that expression in a numeric context.
Furthermore, if the expression has to be coerced from a string and the
string does not begin with a valid number, the stringification operator
returns <code>NaN</code>, the not-a-number value.</p>
<p>That makes it particularly easy to read in numeric data reliably:</p>
<pre>    my $inflation;
    print &quot;Inflation rate: &quot; and $inflation = +&lt;&gt;
        until $inflation != NaN;</pre>
<p>The unary <code>+</code> takes the string returned by <code>&lt;&gt;</code> and converts
it to a number. Or, if the string can't be interpreted as a number,
<code>+</code> returns <code>NaN</code>. Then we just go back and try again until we do get
a valid number.</p>
<p>Note that these new semantics for unary <code>+</code> are a little different
from its role in Perl 5, where it is just the identity operator. In
Perl 5 it's occasionally used to disambiguate constructs like:</p>
<pre>    print  ($x + $y) * $z;        # in Perl 5 means: ( print($x+$y) ) * $z;
    print +($x + $y) * $z;        # in Perl 5 means: print( ($x+$y) * $z );</pre>
<p>To get the same effect in Perl 6, we'd use the adverbial colon instead:</p>
<pre>    print   ($x + $y) * $z;        # in Perl 6 means: ( print($x+$y) ) * $z;
    print : ($x + $y) * $z;        # in Perl 6 means: print( ($x+$y) * $z );</pre>
<a name='Schwartzian pairs'></a><h1>Schwartzian pairs</h1>
<p>Another handy use for pairs is as a natural data structure for
implementing the Schwartzian Transform. This caching technique is used
when sorting a large list of values according to some expensive
function on those values. Rather than writing:</p>
<pre>    my @sorted = sort { expensive($a) &lt;=&gt; expensive($b) } @unsorted;</pre>
<p>and recomputing the same expensive function every time each value is
compared during the sort, we can precompute the function on each value
once. We then pass both the original value and its computed value to
<code>sort</code>, use the computed value as the key on which to sort the list,
but then return the original value as the result. Like this:</p>
<pre>    my @sorted =                        # step 4: store sorted originals
        map  { $_.[0] }                 # step 3: extract original
        sort { $a.[1] &lt;=&gt; $b.[1] }      # step 2: sort on computed
        map  { [$_, expensive($_) ] }   # step 1: cache original and computed
            @unsorted;                  # step 0: take originals</pre>
<p>The use of arrays can make such transforms hard to read (and to
maintain), so people sometimes use hashes instead:</p>
<pre>    my @sorted =                        
        map  { $_.{original} }             
        sort { $a.{computed} &lt;=&gt; $b.{computed} } 
        map  { {original=&gt;$_, computed=&gt;expensive($_)} }   
            @unsorted;</pre>
<p>That improves the readability, but at the expense of performance. Pairs
are an ideal way to get the readability of hashes but with (probably)
even better performance than arrays:</p>
<pre>    my @sorted =                        
        map  { $_.value }             
        sort { $a.key &lt;=&gt; $b.key }  
        map  { expensive($_) =&gt; $_ }     
            @unsorted;</pre>
<p>Or in the case of our example program:</p>
<pre>    @costs = map  { $_.value }
             sort { $a.key &lt;=&gt; $b.key }
             map  { amortize($_) =&gt; $_ }
                 @costs ^* $inflation;</pre>
<p>Note that we also used a hyper-multiplication (<code>^*</code>) to multiply each
cost individually by the rate of inflation before sorting them. That's
equivalent to writing:</p>
<pre>    @costs = map  { $_.value }
             sort { $a.key &lt;=&gt; $b.key }
             map  { amortize($_) =&gt; $_ }
             map  { $_ * $inflation }
                 @costs;</pre>
<p>but spares us from the burden of yet another <code>map</code>.</p>
<p>More importantly, because <code>@costs</code> is an alias for
<code>@%data{$file}{costs}</code>, when we assign the sorted list back to
<code>@costs</code>, we're actually assigning it back into the appropriate
sub-entry of <code>%data</code>.</p>
<a name='The &amp;sum; of all our fears'></a><h1>The &amp;sum; of all our fears</h1>
<p>Perl 6 will probably have a built-in <code>sum</code> operator, but we might
still prefer to build our own for a couple of reasons. Firstly <code>sum</code>
is obviously far too long a name for so fundamental an operation; it
really should be <code>&amp;sum;</code>. Secondly, we may want to extend the basic
summation functionality somehow. For instance, by allowing the user to
specify a filter and only summing those arguments that the filter lets
through.</p>
<p>Perl 6 allows us to create our own operators. Their names can be any
combination of characters from the Unicode set. So it's relatively easy
to build ourselves a <code>&amp;sum;</code> operator:</p>
<pre>    my sub operator:&amp;sum; is prec(\&amp;operator:+($)) (*@list) {
        reduce {$^a+$^b} @list;
    }</pre>
<p>We declare the <code>&amp;sum;</code> operator as a lexically scoped subroutine. The
lexical scoping eases the syntactic burden on the parser, the semantic
burden on other unrelated parts of the code, and the cognitive burden
on the programmer.</p>
<p>The operator subroutine's name is always
<code>operator:whatever_symbols_we_want</code>. In this case, that's
<code>operator:&amp;sum;</code>, but it can be any sequence of Unicode characters,
including alphanumerics:</p>
<pre>        my sub operator:*#@&amp; is prec(\&amp;operator:\)  (STR $x) {
                return &quot;darn $x&quot;;
        }
        my sub operator:&amp;dagger; is prec(\&amp;CORE::kill)  (*@tIHoH) {
                kill(9, @tIHoH) == @tIHoH or die &quot;batlhHa'&quot;;
                return &quot;Qapla!&quot;;
        }
        my sub operator:EQ is prec(\&amp;operator:eq)  ($a, $b) {
                return $a eq $b                 # stringishly equal strings
                    || $a == $b != NaN;         # numerically equal numbers
        }
        # and then:
        warn *#@&amp; &quot;QeH!&quot; unless E&lt;dagger&gt; $puq EQ &quot;Qapla!&quot;;</pre>
<p>Did you notice that cunning <code>$a == $b != NaN</code> test in <code>operator:EQ</code>?
This lovely Perl 6 idiom solves the problem of numerical comparisons
between non-numeric strings.</p>
<p>In Perl 5, a comparison like:</p>
<pre>        $a = &quot;a string&quot;;
        $b = &quot;another string&quot;;
        print &quot;huh?&quot; if $a == $b;</pre>
<p>will unexpectedly succeed (and silently too, if you run without
warnings), because the non-numeric values of both the scalars are
converted to zero in the numeric context of the <code>==</code>.</p>
<p>But in Perl 6, non-numeric strings numerify to <code>NaN</code>. So, using Perl
6's multiway comparison feature, we can add an extra <code>!= NaN</code> to the
equality test to ensure that we compared genuine numbers.</p>
<p>[Update: Now you'd just use <code>===</code> to compare two values within their
type's definition of value equality.]</p>
<p>Meanwhile, we also have to specify a precedence for each new operator
we define. We do that with the <code>is prec</code> trait of the subroutine. The
precedence is specified in terms of the precedence of some existing
operator; in this case, in terms of Perl's built-in unary <code>+</code>:</p>
<pre>    my sub operator:&amp;sum; is prec( \&amp;operator:+($) )</pre>
<p>[Update: Now done with &quot;<code>is equiv</code>&quot;.]</p>
<p>To do this, we give the <code>is prec</code> trait a reference to the existing
operator. Note that, because there are two overloaded forms of
<code>operator:+</code> (unary and binary) of different precedences, to get the
reference to the correct one we need to specify its complete
<i>signature</i> (its name and parameter types) as part of the
enreferencing operation. The ability to take references to signatures
is a standard feature in Perl 6, since ordinary subroutines can also be
overloaded, and may need the same kind of disambiguation when
enreferenced.</p>
<p>If the operator had been binary, we might also have had to specify its
associativity (<code>left</code>, <code>right</code>, or <code>non</code>), using the <code>is assoc</code>
trait.</p>
<p>Note too that we specified the parameter of <code>operator:&amp;sum;</code> with a
flattening asterisk, since we want <code>@list</code> to slurp up any series of
values passed to it, rather than being restricted to accepting only
actual array variables as arguments.</p>
<p>The implementation of <code>operator:&amp;sum;</code> is very simple: we just apply
the built-in <code>reduce</code> function to the list, reducing each successive
pair of elements by adding them.</p>
<p>Note that we used a higher-order function to specify the addition
operation. Larry has decided that the syntax for higher-order functions
requires that implicit parameters be specified with a <code>$^</code> sigil (or
<code>@^</code> or <code>%^</code>, as appropriate) and that the whole expression be
enclosed in braces.</p>
<p>So now we have a <code>&amp;sum;</code> operator:</p>
<pre>    $result = &amp;sum; $wins, $losses, $ties;</pre>
<p>but it doesn't yet provide a way to filter its values. Normally, that
would present a difficulty with an operator like <code>&amp;sum;</code>, whose
<code>*@list</code> argument will gobble up every argument we give it, leaving no
way -- except convention -- to distinguish the filter from the data.</p>
<p>But Perl 6 allows any subroutine -- not just built-ins like
<i><a href='#It is written...'><code>print</code></a></i> -- to take one or more &quot;adverbs&quot; in
addition to its normal arguments. This provides a second channel by
which to transmit information to a subroutine. Typically that
information will be used to modify the behaviour of the subroutine
(hence the name &quot;adverb&quot;). And that's exactly what we need in order to
pass a filter to <code>&amp;sum;</code>.</p>
<p>A subroutine's adverbs are specified as part of its normal parameter
list, but separated from its regular parameters by a colon:</p>
<pre>    my sub operator:&amp;sum; is prec(\&amp;operator:+($)) ( *@list : $filter //= undef) {...</pre>
<p>This specifies that <code>operator:&amp;sum;</code> can take a single scalar adverb,
which is bound to the parameter <code>$filter</code>. When there is no adverb
specified in the call, <code>$filter</code> is default-assigned the value
<code>undef</code>.</p>
<p>We then modify the body of the subroutine to pre-filter the list
through a <code>grep</code>, but only if a filter is provided:</p>
<pre>        reduce {$^a+$^b}  ($filter ?? grep &amp;$filter, @list :: @list);
    }</pre>
<p>The <code>??</code> and <code>::</code> are the new way we write the old <code>?:</code> ternary
operator in Perl 6. Larry had to change the spelling because he needed
the single colon for marking adverbs. But it's a change for the better
anyway --it was rather odd that all the other short-circuiting logical
operators (<code>&amp;&amp;</code> and <code>||</code> and <code>//</code>) used doubled symbols, but the
conditional operator didn't. Well, now it does. The doubling also helps
it stand out better in code, in part because it forces you to put space
around the <code>::</code> so that it's not confused with a package name
separator.</p>
<p>[Update: We've changed <code>::</code> to <code>!!</code> to reduce that confusion, and because
of the ? vs ! symbology of true? vs false? that pervades the rest of Perl 6.]</p>
<p>You might also be wondering about the ambiguity of <code>??</code>, which in Perl
5 already represents an empty regular expression with question-mark
delimiters. Fortunately, Perl 6 won't be riddled with the nasty
<code>?...?</code> regex construct, so there's no ambiguity at all.</p>
<p>Adverbial semantics can be defined for <i>any</i> Perl 6 subroutine. For
example:</p>
<pre>    sub mean (*@values : $type //= 'arithmetic') {
        given ($type) {
            when 'arithmetic': { return sum(@values) / @values; }
            when 'geometric':  { return product(@values) ** (1/@values) }
            when 'harmonic':   { return @values / sum( @values ^** -1 ) }
            when 'quadratic':  { return (sum(@values ^** 2) / @values) ** 0.5 }
        }
        croak &quot;Unknown type of mean: '$type'&quot;;
    }</pre>
<p>Adverbs will probably become widely used for passing this type of
&quot;out-of-band&quot; behavioural modifier to subroutines that take an
unspecified number of data arguments.</p>
<p>[Update: Nowadays any named parameter may be specified adverbially.]</p>
<a name='Would you like an adverb with that?'></a><h1>Would you like an adverb with that?</h1>
<p>OK, so now our <code>&amp;sum;</code> operator can take a modifying filter. How
exactly do we pass that filter to it?</p>
<p>As described <i><a href='#It is written...'>earlier</a></i>, the colon is used to
introduce adverbial arguments into the argument list of a subroutine or
operator. So to do a normal summation we write:</p>
<pre>    $sum = &amp;sum; @costs;</pre>
<p>whilst to do a filtered summation we place the filter after a colon at
the end of the regular argument list:</p>
<pre>    $sum = &amp;sum; @costs : sub {$_ &gt;= 1000};</pre>
<p>or, more elegantly, using a higher-order function:</p>
<pre>    $sum = &amp;sum; @costs : {$^_ &gt;= 1000};</pre>
<p>Any arguments after the colon are bound to the parameters specified by
the subroutine's adverbial parameter list.</p>
<p>[Update: Now you'd probably just write:</p>
<pre>    $sum = &amp;sum; @costs, :filter{$_ &gt;= 1000};</pre>
<p>or just</p>
<pre>    $sum = [+] grep {$_ &gt;= 1000}, @costs;</pre>
<p>]</p>
<p>Note that the example also demonstrates that we can interpolate the
results of the various summations directly into output strings. We do
this using Perl 6's scalar interpolation mechanism (<code>$(...)</code>), like
so:</p>
<pre>    print &quot;Total expenditure: $( &amp;sum; @costs )\n&quot;;
    print &quot;Major expenditure: $( &amp;sum; @costs : {$^_ &gt;= 1000} )\n&quot;;
    print &quot;Minor expenditure: $( &amp;sum; @costs : {$^_ &lt; 1000} )\n&quot;;</pre>
<a name='The odd lazy step'></a><h1>The odd lazy step</h1>
<p>Finally (and only because we <i>can</i>), we print out a list of every
second element of <code>@costs</code>. There are numerous ways to do that in Perl
6, but the cutest is to use a lazy, infinite, stepped list of indices
in a regular slicing operation.</p>
<p>In Perl 6, any list of values created with the <code>..</code> operator is
created lazily. That is, the <code>..</code> operator doesn't actually build a
list of all the values in the specified range, it creates an array
object that knows the boundaries of the range and can interpolate (and
then cache) any given value when it's actually needed. That's useful,
because it greatly speeds up the creation of a list like <code>(1..Inf)</code>.</p>
<p><code>Inf</code> is Perl 6's standard numerical infinity value, so a list that
runs to <code>Inf</code> takes ... well ... forever to actually build. But
writing <code>1..Inf</code> is OK in Perl 6, since the elements of the resulting
list are only ever computed on demand. Of course, if you were to
<code>print(1..Inf)</code>, you'd have plenty of time to go and get a cup of
coffee. And even then (given the comparatively imminent heat death of
the universe) that coffee would be <i>really</i> cold before the output was
complete. So there will probably be a warning when you try to do that.</p>
<p>But to get an infinite list of odd indices, we don't want every number
between 1 and infinity; we want every <i>second</i> number. Fortunately,
Perl 6's <code>..</code> operator can take an adverb that specifies a &quot;step-size&quot;
between the elements in the resulting list. So if we write <code>(1..Inf :
2)</code>, we get <code>(1,3,5,7,...)</code>. Using that list, we can extract the oddly
indexed elements of an array of any size (e.g. <code>@costs</code>) with an
ordinary array slice:</p>
<pre>    print @costs[1..Inf:2]</pre>
<p>You might have expected another one of those &quot;maximal-entropy coffee&quot;
delays whilst <code>print</code> patiently outputs the infinite number of
<code>undef</code>'s that theoretically exist after <code>@costs</code>' last element, but
slices involving infinite lists avoid that problem by returning only
those elements that actually exist in the list being sliced. That is,
instead of iterating the requested indices in a manner analogous to:</p>
<pre>    sub slice is lvalue (@array, *@wanted_indices) {
        my @slice;
        foreach $wanted_index ( @wanted_indices ) {
            @slice[+@slice] := @array[$wanted_index];
        }
        return @slice;
    }</pre>
<p>infinite slices iterate the available indices:</p>
<pre>    sub slice is lvalue (@array, *@wanted_indices) {
        my @slice;
        foreach $actual_index ( <a href='mailto:0..@array.last'>0..@array.last</a> ) {
            @slice[+@slice] := @array[$actual_index]
                if any(@wanted_indices) == $actual_index;
        }
        return @slice;
    }</pre>
<p>(Obviously, it's actually far more complicated -- and lazy -- than
that. It has to preserve the original ordering of the wanted indexes,
as well as cope with complex cases like infinite slices of infinite
lists. But from the programmer's point of view, it all just DWYMs).</p>
<p>[Update: Now we write that <code>1..*</code> to better indicate that the top bound is
not <code>Inf</code> but &quot;Whatever&quot;.]</p>
<p>By the way, binding selected array elements to the elements of another
array (as in: <code>@slice[+@slice] := @array[$actual_index]</code>), and then
returning the bound array as an lvalue, is a neat Perl 6 idiom for
recreating any kind of slice-like semantics with user-defined
subroutines.</p>
<a name='Take that! And that!'></a><h1>Take that! And that!</h1>
<p>And so, lastly, we save the data back to disk:</p>
<pre>    save_data(%data, log =&gt; {name=&gt;'metalog', vers=&gt;1, costs=&gt;[], stat=&gt;0});</pre>
<p>Note that we're passing in both a hash and a pair, but that these still
get correctly folded into <code>&amp;save_data</code>'s single hash parameter,
courtesy of the flattening asterisk on the parameter definition:</p>
<pre>    sub save_data (*%data) {...</pre>
<a name='In a nutshell...'></a><h1>In a nutshell...</h1>
<p>It's okay if your head is spinning at this point.</p>
<p>We just crammed a huge number of syntactic and semantic changes into a
comparatively small piece of example code. The changes may seem
overwhelming, but that's because we've been concentrating on <i>only</i>
the changes. Most of the syntax and semantics of Perl's operators don't
change at all in Perl 6.</p>
<p>So, to conclude, here's a summary of what's new, what's different, and
(most of all) what stays the same.</p>
<a name='Unchanged operators'></a><h2>Unchanged operators</h2>
<ul>
<li><a name='prefix and postfix ++ and --'></a>prefix and postfix <code>++</code> and <code>--</code></li>
<li><a name='unary !, ~, \, and -'></a>unary <code>!</code>, <code>~</code>, <code>\</code>, and <code>-</code></li>
<p>[Update: <code>~</code> is now <code>+^</code> or <code>~^</code>, and <code>\</code> now builds a <code>Capture</code> object
that degenerates to reference semantics.]</p>
<li><a name='binary **'></a>binary <code>**</code></li>
<li><a name='binary =~ and !~'></a>binary <code>=~</code> and <code>!~</code></li>
<p>[Update: Smartmatch is now <code>~~</code>.]</p>
<li><a name='binary *, /, and %'></a>binary <code>*</code>, <code>/</code>, and <code>%</code></li>
<li><a name='binary + and -'></a>binary <code>+</code> and <code>-</code></li>
<li><a name='binary &lt;&lt; and &gt;&gt;'></a>binary <code>&lt;&lt;</code> and <code>&gt;&gt;</code></li>
<p>[Update: Now <code>+&lt;</code> or <code>~&lt;</code> and <code>+&gt;</code> or <code>~&gt;</code>.]</p>
<li><a name='binary &amp; and |'></a>binary <code>&amp;</code> and <code>|</code></li>
<p>[Update: <code>&amp;</code> is now <code>+&amp;</code> or <code>~&amp;</code>, while <code>|</code> is now <code>+|</code> or <code>~|</code>.]</p>
<li><a name='binary =, +=, -=, *=, etc.'></a>binary <code>=</code>, <code>+=</code>, <code>-=</code>, <code>*=</code>, etc.</li>
<li><a name='binary ,'></a>binary <code>,</code></li>
<li><a name='unary not'></a>unary <code>not</code></li>
<li><a name='binary and, or, and xor'></a>binary <code>and</code>, <code>or</code>, and <code>xor</code></li>
</ul>
<a name='Changes to existing operators'></a><h2>Changes to existing operators</h2>
<ul>
<li><a name='binary -&gt; (dereference) becomes .'></a>binary <code>-&gt;</code> (dereference) becomes <code>.</code></li>
<li><a name='binary . (concatenate) becomes _'></a>binary <code>.</code> (concatenate) becomes <code>_</code></li>
<p>[Update: <code>~</code> instead.]</p>
<li><a name='unary + (identity) now enforces numeric context on its argument'></a>unary <code>+</code> (identity) now enforces numeric context on its
argument</li>
<li><a name='binary ^ (bitwise xor) becomes ~'></a>binary <code>^</code> (bitwise xor) becomes <code>~</code></li>
<p>[Update: No, it becomes <code>+^</code> or &lt;~^&gt;.]</p>
<li><a name='binary =&gt; becomes the &quot;pair&quot; constructor'></a>binary <code>=&gt;</code> becomes the &quot;pair&quot; constructor</li>
<li><a name='ternary ? : bbeeccoommeess ?? ::'></a>ternary <code>? :</code> bbeeccoommeess <code>?? ::</code></li>
<p>[Update: <code>??!!</code>.]</p>
</ul>
<a name='Enhancements to existing operators'></a><h2>Enhancements to existing operators</h2>
<ul>
<li><a name='binary .. becomes even lazier'></a>binary <code>..</code> becomes even lazier</li>
<p>[Update: All lists are lazy by default now.]</p>
<li><a name='binary &lt;, &gt;, lt, gt, ==, !=, etc. become chainable'></a>binary <code>&lt;</code>, <code>&gt;</code>, <code>lt</code>, <code>gt</code>, <code>==</code>, <code>!=</code>, etc.
become chainable</li>
<li><a name='Unary -r, -w, -x, etc. are nestable'></a>Unary <code>-r</code>, <code>-w</code>, <code>-x</code>, etc. are nestable</li>
<li><a name='The &lt;&gt; input operator are more context-aware'></a>The <code>&lt;&gt;</code> input operator are more context-aware</li>
<p>[Update: prefix:&lt;=&gt; is now the iterator iterater.]</p>
<li><a name='The logical &amp;&amp; and || operators propagate their context to both their operands'></a>The logical <code>&amp;&amp;</code> and <code>||</code> operators propagate their context
to <i>both</i> their operands</li>
<li><a name='The x repetition operator no longer requires listifying parentheses on its left argument in a list context.'></a>The <code>x</code> repetition operator no longer requires listifying
parentheses on its left argument in a list context.</li>
<p>[Update: The list-repeating form is now <code>xx</code> instead.]</p>
</ul>
<a name='New operators:'></a><h2>New operators:</h2>
<ul>
<li><a name='unary _ is the explicit string context enforcer'></a>unary <code>_</code> is the explicit string context enforcer</li>
<p>[Update: <code>~</code>.]</p>
<li><a name='binary ~~ is high-precedence logical xor'></a>binary <code>~~</code> is high-precedence logical xor</li>
<p>[Update: <code>^^</code>.]</p>
<li><a name='unary * is a list context specifier for parameters and a array flattening operator for arguments'></a>unary <code>*</code> is a list context specifier for parameters and a array
flattening operator for arguments</li>
<p>[Update: Use <code>[,]</code> for arguments.]</p>
<li><a name='unary ^ is a meta-operator for specifying vector operations'></a>unary <code>^</code> is a meta-operator for specifying vector operations</li>
<p>[Update: »op« now.]</p>
<li><a name='unary := is used to create aliased variables (a.k.a. binding)'></a>unary <code>:=</code> is used to create aliased variables (a.k.a. binding)</li>
<li><a name='unary // is the logical 'default' operator'></a>unary <code>//</code> is the logical 'default' operator</li>
</ul>
</div>
